package com.xfp.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xfp.mapper.RegionMapper;
import com.xfp.method.pageTotal;
import com.xfp.pojo.dto.NodeDto;
import com.xfp.pojo.entity.Business;
import com.xfp.pojo.entity.Node;
import com.xfp.pojo.entity.Region;
import com.xfp.pojo.dto.RegionDto;
import com.xfp.pojo.dto.RegionQueryDto;
import com.xfp.pojo.vo.RegionDetailedQueryVo;
import com.xfp.pojo.vo.RegionQueryVo;
import com.xfp.service.RegionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.cli.Digest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
@Slf4j
public class RegionServiceImp implements RegionService {

    @Autowired
    private RegionMapper regionMapper;

    /**
     * 新增区域实现
     * @param dto
     */
    @Override
    public void insertRegion(RegionDto dto) throws Exception {
        long l = System.currentTimeMillis();
        dto.setId(l);
        int n = regionMapper.insertRegion(dto);
        if(n!=1){
            throw new Exception("新增区域失败");
        }
    }

    /**
     * 修改区域
     * @param regionId
     */
    @Override
    public void updateRegion(Long regionId,RegionDto dto) throws Exception {
        int n = regionMapper.updateRegion(regionId,dto);
        if(n!=1)
            throw new Exception("修改区域");
    }

    /**
     * 删除区域
     * @param regionId
     */
    @Override
    public void delete(Long regionId) throws Exception {
        int n = regionMapper.delete(regionId);
        if(n!=1)
            throw new Exception("删除区域失败");
    }

    /**
     * 区域搜索实现
     * @param dto
     * @return
     */
    @Override
    public RegionQueryVo pageRegion(RegionQueryDto dto) throws Exception {
        //进行安全校验
        dto.check();
        //使用分页插件
        PageHelper.startPage(dto.getPageIndex(),dto.getPageSize());
        Page<Region> page = regionMapper.pageRegion(dto);
        //添加点位数
        page.forEach(p->{
            int n = regionMapper.countVm(p.getId());
            p.setNodeCount(n);
        });
        //计算总页数
        Long l = pageTotal.total(page.getTotal(),dto.getPageSize());
        //添加数据
        RegionQueryVo vo = RegionQueryVo.builder()
                .pageIndex(dto.getPageIndex())
                .pageSize(dto.getPageSize())
                .totalPage(page.getTotal())
                .totalCount(l)
                .currentPageRecords(page.getResult())
                .build();
        return vo;
    }

}
